﻿
package com.hh.bss.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;



/**
 * 
 * <p>Title: </p>
 * <p>Description: </p>
 */
public class HTTPHelper {
	/**
	 * 若某应用的网站根目录为：http://www.apache.org/java/
	 * 
	 * @param request HttpServletRequest : http请求
	 * @return String : 返回相应的应用根URL，如：http://www.apache.org/java/
	 */
	public static String getServerPath(final HttpServletRequest request){
		String uri = request.getRequestURI();
		String url = request.getRequestURL().toString();
		return url.substring(0, url.indexOf(uri)) + request.getContextPath() + "/";
	}
	/**
	 * 读取String参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @return String : 返回参数对应的String值，如果无对应的参数，则返回null
	 */
	public static String getParameter(HttpServletRequest request, String name){
		return request.getParameter(name);
	}
	/**
	 * 读取String参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @param defaultValue String : 默认值
	 * @return String :返回参数对应的String值，如果无对应的参数，则返回默认值defaultValue
	 */
	public static String getParameter(HttpServletRequest request, String name, String defaultValue){
		String value = request.getParameter(name);
		if(value == null) return defaultValue;
		return value;
	}
	/**
	 * 读取int参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @return int : 参数对应的int值，如果是非int型的参数，则抛出运行时的转换异常
	 */
	public static int getParameterInt(HttpServletRequest request, String name){
		return Integer.parseInt(getParameter(request, name));
	}
	/**
	 * 读取int参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @param defaultValue int : 默认值
	 * @return int : 参数对应的int值，若参数无效，则返回默认值
	 */
	public static int getParameterInt(HttpServletRequest request, String name, int defaultValue){
		return StringHelper.parseInt(getParameter(request, name), defaultValue);
	}
	/**
	 * 读取long参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @return long : 返回参数对应的long值，若参数无效，则抛出运行时的转换异常
	 */
	public static long getParameterLong(HttpServletRequest request, String name){
		return Long.parseLong(getParameter(request, name));
	}
	/**
	 * 读取long参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @param defaultValue long : 默认值
	 * @return long : 参数对应的long值，若参数无效，则返回默认值
	 */
	public static long getParameterLong(HttpServletRequest request, String name, long defaultValue){
		return StringHelper.parseLong(getParameter(request, name), defaultValue);
	}
	/**
	 * 读取double参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @return double : 返回参数对应的double值，若参数无效，则抛出运行时的转换异常
	 */
	public static double getParameterDouble(HttpServletRequest request, String name){
		return Double.parseDouble(getParameter(request, name));
	}
	/**
	 * 读取double参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @param defaultValue double : 默认值
	 * @return double : 参数对应的double值，若参数无效，则返回默认值
	 */
	public static double getParameterDouble(HttpServletRequest request, String name, double defaultValue){
		return StringHelper.parseDouble(getParameter(request, name), defaultValue);
	}
	/**
	 * 读取java.sql.Date参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @return java.sql.Date : 返回参数对应的java.util.Date值（字符串格式为yyyy-MM-dd），若参数无效，则返回null
	 */
	public static Date getParameterDate(HttpServletRequest request, String name){
		final String format = "yyyy-MM-dd";
		return getParameterDate(request, name, format);
	}
	/**
	 * 读取java.util.Date参数
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 参数名
	 * @param format String : 日期格式
	 * @return java.util.Date : 按日期格式将参数值转换为java.util.Date后返回，若参数无效，则返回null
	 */
	public static Date getParameterDate(HttpServletRequest request, String name, String format){
		String value = getParameter(request, name);
		if(DateHelper.isDateFormat(value, format) == false) return null;
		return DateHelper.toDate(value, format);
	}
	/**
	 * 读取session内某属性
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : 属性名
	 * @return Object : 属性值，若没有相应的属性，则返回null
	 */
	public static Object getSessionAttribute(HttpServletRequest request, String name){
		HttpSession session = request.getSession(true);
		return session.getAttribute(name);
	}
	/**
	 * 自底向上读取request里的某属性,相当于<br> request.getParameter(name);<br> (String)request.getAttribute(name);<br>
	 * (String)request.getSession().getAttribute(name);<br>
	 * (String)request.getSession().getServletContext().getAttribute(name)
	 * 
	 * @param request HttpServletReqeust : http请求
	 * @param name String : 属性名
	 * @return String : 属性值，转换为String类型
	 */
	public static String getRequestValue(HttpServletRequest request, String name){
		String value = request.getParameter(name);
		if(value != null) return value;
		value = (String) request.getAttribute(name);
		if(value != null) return value;
		HttpSession session = request.getSession(true);
		value = (String) session.getAttribute(name);
		if(value != null) return value;
		value = (String) session.getServletContext().getAttribute(name);
		return value;
	}
	/**
	 * 根据名字取得相应的cookie
	 * 
	 * @param request HttpServletRequest : http请求
	 * @param name String : cookie名称
	 * @return Cookie : 相应的cookie,如果没有则返回null
	 */
	public static Cookie getCookie(HttpServletRequest request, String name){
		Cookie[] cookies = request.getCookies();
		if(cookies == null || cookies.length <= 0) return null;
		for (int i = 0; i < cookies.length; i++){
			Cookie cookie = cookies[i];
			if(cookie.getName().equals(name)) return cookie;
		}
		return null;
	}
	/**
	 * 得到HttpServletRequest里的所有请求参数的描述
	 * 
	 * @param request HttpServletRequest : http请求
	 * @return String : 描述
	 */
	public static String getAllParametersDesc(final HttpServletRequest request){
		Enumeration names = request.getParameterNames();
		StringBuffer params = new StringBuffer();
		params.append("[");
		while(names.hasMoreElements()){
			String name = (String) names.nextElement();
			String value = request.getParameter(name);
			params.append(name).append("=").append(value).append(";");
		}
		params.append("]");
		return params.toString();
	}
	/**
	 * 取得某URL的信息流
	 * 
	 * @param url URL : 网点URL
	 * @return InputStream : 信息流
	 * @throws IOException :
	 */
	public static InputStream getURLInputStream(final URL url) throws IOException{
		InputStream in = url.openStream();
		return in;
	}
	/**
	 * 取得某URL的信息流
	 * 
	 * @param url String : 网点URL字符串表示
	 * @return InputStream : 信息流
	 * @throws MalformedURLException : 当字符串URL为错误的URL地址时抛出
	 * @throws IOException :
	 */
	public static InputStream getURLInputStream(final String url) throws MalformedURLException,IOException{
		URL u = new URL(url);
		return getURLInputStream(u);
	}

	/**
	 * 得到某网点的所有信息
	 * 
	 * @param url URL : 网点URL
	 * @return String : 网点上的所有信息
	 * @throws IOException :
	 */
	public static String getURLString(final URL url) throws IOException{
		StringBuffer result = new StringBuffer();
		InputStream in = url.openStream();		
		int c;
		while((c = in.read()) != -1){
			result.append((char) c);
		}
		return result.toString();
	}
	/**
	 * 得到某网点的所有信息
	 * 
	 * @param url String : 网点URL字符串表示
	 * @return String : 网点上的所有信息
	 * @throws MalformedURLException : 当字符串URL为错误的URL地址时抛出
	 * @throws IOException :
	 */
	public static String getURLString(final String url) throws MalformedURLException,IOException{
		URL u = new URL(url);
		return getURLString(u);
	}
	/**
	 * 代替URLEncoder.encode方法
	 * @param in String : 
	 * @return String : URLEncode之后的值
	 */
	public static String encode(final String in){
		return URLEncoder.encode(in);
	}
	
	/**
	 * 代替URLDecoder.decode方法
	 * @param in String : 
	 * @return String :
	 */
	public static String decode(final String in){
		return URLDecoder.decode(in);
	}
	
//	/**
//	 * @param url String : 网站URL字符串表示
//	 * @param timeout int : 超时毫秒数,0表示采用默认超时策略
//	 * @return String : 网站URL上的所有信息
//	 */
//	public static String doHttpGet(final String url, final int timeout){
//		return doHttpSend(url, "GET", null, timeout, null, null);
//	}
//
//	/**
//	 * @param url String : 网站URL字符串表示
//	 * @param content String : POST时要发送的数据
//	 * @param timeout int : 超时毫秒数,0表示采用默认超时策略
//	 * @return String : 网站URL上的所有信息
//	 */
//	public static String doHttpPost(final String url, final String content, final int timeout){
//		return doHttpSend(url, "POST", content, timeout, null, null);
//	}
//
//	/**
//	 * @param url String : 网站URL字符串表示
//	 * @param method String : POST/GET/HEAD
//	 * @param content String : POST时要发送的数据
//	 * @param reqHeaders Map : 请求头信息，多个头/值封装成Map
//	 * @param resHeaders Map : 请求头信息，多个头/值封装成Map
//	 * @param timeout int : 超时毫秒数,0表示采用默认超时策略
//	 * @return String : 网站URL上的所有信息
//	 */
//	public static String doHttpSend(final String url, final String method, final String content, final int timeout,
//			final Map reqHeaders, Map resHeaders){
//		//
//		HttpConnection http = new HttpConnection();
//		if(timeout > 0) http.setTimeout(timeout);
//		if(reqHeaders != null){
//			for (Iterator it = reqHeaders.keySet().iterator(); it.hasNext();){
//				String key = (String) it.next();
//				String value = (String) reqHeaders.get(key);
//				http.addHeader(key, value);
//			}
//		}
//		if("POST".equalsIgnoreCase(method)){
//			http.doPost(url, content);
//		}else if("HEAD".equalsIgnoreCase(method)){
//			http.doHead(url);
//		}else{
//			// GET
//			http.doGet(url);
//		}
//		resHeaders = http.getRespnseHeaders();
//		return http.getResponseText();
//	}
	public static String httpSend(final String url, String method, String content, Map reqHeaders, Map resHeaders)
			throws Exception{
		StringBuffer sb = new StringBuffer();
		method = method.toUpperCase();
		URL uurl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) uurl.openConnection();
		conn.setRequestMethod(method);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		if(reqHeaders != null){
			for (Iterator itor = reqHeaders.keySet().iterator(); itor.hasNext();){
				String key = (String) itor.next();
				String value = (String) reqHeaders.get(key);
				if(value != null){
					conn.setRequestProperty(key, value);
				}
			}
		}
		if("POST".equalsIgnoreCase(method)){
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
			writer.write(content);
			writer.close();
		}
		if(resHeaders != null){
			for (Iterator itor = conn.getHeaderFields().keySet().iterator(); itor.hasNext();){
				String key = (String) itor.next();
				String value = conn.getHeaderField(key);
				resHeaders.put(key, value);
			}
		}
		if(conn.getResponseCode() == 200){
			InputStream in = conn.getInputStream();
			for (int c = -1; (c = in.read()) != -1;){
				sb.append((char) c);
			}
		}
		return sb.toString();
	}

	
	public static void main(String[] args) throws IOException{
	}
}
